package com.xinyue.exceltool.logic;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

/**
 * 模板信息配置
 *
 * @author wang guang shuai
 */
@Service
public class CodeTemplateService {

    private static Logger logger = LoggerFactory.getLogger(CodeTemplateService.class);
    private static Configuration config;

    @PostConstruct
    public void start() {
        config = new Configuration(Configuration.VERSION_2_3_30);
        try {
            config.setClassForTemplateLoading(this.getClass(), "/templates");
            config.setDefaultEncoding("UTF-8");
        } catch (Exception e) {
            logger.error("初始化模板信息失败", e);
            System.exit(1);
        }
    }

    public static void outFile(String templateName, File targetFile, Object data) {
        if (config == null) {
            logger.error("未初始化配置信息");
            return;
        }
        try {
            Template template = config.getTemplate(templateName);
            try (Writer writer = new FileWriter(targetFile)) {
                template.process(data, writer);
                writer.flush();
            } catch (Exception e) {
                logger.error("根据模板生成文件失败", e);
                System.exit(0);
            }

        } catch (IOException e) {
            logger.error("根据模板生成文件失败", e);
        }

    }
}
